Sorting

This applet demonstrates array sorting. Use the form below to add values to the array. Type in the box labelled Data and tap [Add to Array] to insert data at the front of the array. Tap on the [Sort] button to sort them using a simple bubble sort. This will sort in "dictionary" order because all values are stored as strings. The string "1" comes before "11", which in turn comes before "2", and that before "ab". This same algorithm would sort in numeric order if you pass it an array of numbers, but this applet sends it strings.

Array
Data


Discussion

The bubble sort algorithm pushes the biggest values to the top of the array one at a time. This example uses both local variables (scoped within a function) and global variables (used by many functions, e.g., myArray and arrayTop).
// Sort the array using a simple bubblesort
function sort()
{
    for (var i = 0; i < arrayTop; i++)
    {
        for (var j = i; j < arrayTop; j++)
            if (myArray[i] < myArray[j])
            {
                // out of order: swap them.
                var tmp = myArray[i]
                myArray[i] = myArray[j]
                myArray[j] = tmp
            }
    }
    showArray()
}
Copyright ©1998 by Charles River Media, All Rights Reserved